package edu.xust.dao.impl;


import edu.xust.config.Repository;
import edu.xust.config.Resource;
import edu.xust.dao.DriversDao;
import edu.xust.entity.Drivers;
import edu.xust.entity.DriversExample;
import edu.xust.mapper.DriversMapper;
import edu.xust.page.PageInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;


@Repository("driversDao")
public class DriversDaoImpl implements DriversDao {

    @Resource
     DriversMapper driversMapper;
    /*static DriversMapper driversMapper;
    static {
        Reader reader = null;//读取根目录下的confi.xml
        try {
            reader = Resources.getResourceAsReader("config.xml");

            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();//通过连接会话工厂得到一个连接
            driversMapper = sqlSession.getMapper(DriversMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

    @Override
    public List<Drivers> getDriversByPage(PageInfo pageInfo) throws Exception {
        DriversExample driversExample = new DriversExample();
        long l = driversMapper.countByExample(null);
        pageInfo.setItemCount((int)l);//总页数
        driversExample.setOffset(pageInfo.getOffset());//第几页
        driversExample.setLimit(pageInfo.getPageSize());//每页多少条
        return driversMapper.selectByExample(driversExample);
    }


    /**
     * 添加司机
     * @param drivers
     * @return
     * @throws Exception
     */
    @Override
    public Integer addDrivers(Drivers drivers){

        return driversMapper.insertSelective(drivers);
    }

    /**
     * 根据id查询单个司机
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Drivers getDriverById(String id) throws Exception {
        return driversMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据司机编号查询货单信息
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Drivers getDriversWithOrder(String id) throws Exception {
        return driversMapper.getDriversWithTransportbills(id);
    }

    /**
     * 修改司机信息
     * @param drivers
     * @return
     */
    @Override
    public Integer editDrivers(Drivers drivers) {
        return driversMapper.updateByPrimaryKey(drivers);
    }

    /**
     * 根据id删除司机
     * @param id
     * @return
     */
    @Override
    public Integer deleteDrivers(String id) {
        return driversMapper.deleteByPrimaryKey(id);
    }
}
